
// var serverUrl = "https://ywzb.ywkj.online";
// var serverUrl = "http://192.168.0.123:8089";
// var serverUrl = "https://266k745z96.yicp.fun";

var serverUrl = "https://cloud.quwk.cn/canteenapi";




// 请求头处理函数
function CreateHeader(url, type) {
  let header = {}
  header = {
    'content-type': 'application/json'
  }

  const id = wx.getStorageSync('id');
  const openid = wx.getStorageSync('openid');


  if(!id || !openid){
    wx.redirectTo({
      url: '/pages/user/authorize/index',
    })

  }
  // const token = wx.getStorageSync("token") || "";
  // header['Authorization'] = `yyjl${token}`;
  // if (type == 'POST_PARAMS') {
  //   header = {
  //     'content-type': 'application/json'
  //     // 'content-type': 'application/json;charset=UTF-8'
  //   }
  // } else {
  //   header = {
  //     'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
  //     // 'content-type': 'application/json;charset=UTF-8'
  //   }
  // }
  // if (exceptionAddrArr.indexOf(url) == -1) { //排除请求的地址不需要token的地址
  //   let token = wx.getStorageSync("authorize_token");
  //   header['access-token'] = token;
  // }
  return header;
}

//post请求，数据在body中

function postRequest(url, data) {
  let header = CreateHeader(url, 'POST');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          if (res.data.code == 401) {
            showLoginTimeOut()
            reject(res)
          } else {
            resolve(res)
          }
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}

//post请求，数据按照query方式传给后端
function postParamsRequest(url, data) {
  let header = CreateHeader(url, 'POST_PARAMS');
  let useurl = url;
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + useurl,
      data: data,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          if (res.data.code == 401) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: '登录超时，请点击确认重新登录',
              showCancel: false,
              complete: (res2) => {
                if (res2.confirm) {
                  getToken()
                }
              }
            })
            reject(res)

          } else {
            resolve(res)
          }
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}

function getToken() {
  wx.login({
    success: res => {
      if (res.code) {
        const code = res.code
        wx.showLoading({
          title: "登录中"
        })
        wx.request({
          url: serverUrl + "/bmjt/yyjlService/getUserInfoByOpenid",
          data: {
            code
          },
          method: 'GET',
          success: (res1 => {
            if (res1.statusCode === 200) {
              const {
                openid,
                rylx,
                unionid,
                certificate_code,
                user_name,
                mobile,
                token
              } = res1.data.data
              wx.setStorageSync('openid', openid);
              wx.setStorageSync('rylx', rylx);
              wx.setStorageSync('unionid', unionid);
              wx.setStorageSync('certificate_code', certificate_code);
              wx.setStorageSync('user_name', user_name);
              wx.setStorageSync('mobile', mobile);
              wx.setStorageSync('token', token)

            } else {
              wx.showToast({
                title: 'Token异常',
                icon: 'none'
              })
            }
          }),
          fail: (res => {
            wx.showToast({
              title: 'Token异常',
              icon: 'none'
            })
          }),
          complete: (() => {
            wx.hideLoading()

            wx.redirectTo({
              url: '/pages/index/index',
            })


          })
        })

      }
    },
    fail() {
      wx.showToast({
        title: '系统异常',
        icon: 'none'
      })
    }
  })
}


function showLoginTimeOut() {
  wx.hideLoading()
  wx.showModal({
    title: '提示',
    content: '登录超时，请点击确认重新登录',
    showCancel: false,
    complete: (res) => {
      if (res.confirm) {
        getToken()
        
      }
    }
  })

}



//get 请求
function getRequest(url, data) {
  let header = CreateHeader(url, 'GET');
  const pages = getCurrentPages();

  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'GET',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          if (res.data.code == 401) {
            showLoginTimeOut()
            // reject(res)

          } else {
            resolve(res)
          }
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })


}


//put请求
function putRequest(url, data) {
  let header = CreateHeader(url, 'PUT');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'PUT',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}

//delete请求
function deleteRequest(url, data) {
  let header = CreateHeader(url, 'delete');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'DELETE',
      success: (res => {
        if (res.statusCode === 200) {
          //200: 服务端业务处理正常结束
          resolve(res)
        } else {
          reject(res)
        }
      }),
      fail: (res => {
        reject(res)
      })
    })
  })
}

module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;
module.exports.postParamsRequest = postParamsRequest;
module.exports.putRequest = putRequest;
module.exports.deleteRequest = deleteRequest;